package com.example.redis.exception;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.lock.exception.LockFailureException;
import com.example.redis.common.enums.ResponseCode;
import com.example.redis.domain.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import java.util.Set;

/**
 * 全局异常处理器
 *
 * @author ruoyi
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 请求方式不支持
     */
    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public ResultVO handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException e,
                                                        HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',不支持'{}'请求", requestURI, e.getMethod());
        return ResultVO.fail(e.getMessage());
    }

    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public ResultVO handleServiceException(ServiceException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生业务异常:{}", requestURI, e.getMessage());
        Integer code = e.getCode();
        return ObjectUtil.isNotNull(code) ? ResultVO.fail(code, e.getMessage()) : ResultVO.fail(e.getMessage());
    }

    @ExceptionHandler(RuntimeException.class)
    public ResultVO handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生未知异常.", requestURI, e.getMessage());
        return ResultVO.fail(ResponseCode.ERROR);
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}',发生系统异常.", requestURI, e);
        return ResultVO.fail(e.getMessage());
    }


    /**
     * 参数校验
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = {BindException.class, MethodArgumentNotValidException.class})
    public ResultVO argumentNotValidException(Exception e, HttpServletRequest request) {
        //1.拿到绑定结果
        BindingResult bindingResult;
        if (e instanceof BindException) {
            bindingResult = ((BindException) e).getBindingResult();
        } else {
            bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
        }

        String message = wrapperBindingResult(bindingResult);
        log.warn("GlobalException:参数校验异常:URI:{}", request.getRequestURI());
        return ResultVO.fail(ResponseCode.METHOD_ARGUMENT_NOT_VALID.getCode(), message);
    }

    /**
     * 处理返回数据
     *
     * @param bindingResult
     * @return
     */
    private String wrapperBindingResult(BindingResult bindingResult) {
        // 默认赋值 参数异常
        StringBuilder errorMessage = new StringBuilder();
        // 获取所有校验出错的属性的默认提示语
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMessage.append(fieldError.getField()).append("-").append(fieldError.getDefaultMessage()).append(";");
        }
        return errorMessage.toString();
    }

    /**
     * 验证请求时候的参数(该用法适用于方法所在的Controller上加注解@Validated,并且GET请求参数被JSR303修饰)
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultVO handleServiceException(ConstraintViolationException e, HttpServletRequest request) {
        log.warn("GlobalException:请求发生异常 ,参数验证失败,URL:{} ", request.getRequestURI());

        Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
        StringBuilder errorMessage = new StringBuilder();

        for (ConstraintViolation<?> constraintViolation : violations) {
            Path propertyPath = constraintViolation.getPropertyPath();//此时拿到的参数名称为:方法名:参数名,所以需要处理一下,只保留参数名
            String property = propertyPath.toString();
            property = property.substring(property.indexOf(".") + 1, property.length());
            String message = constraintViolation.getMessage();
            errorMessage.append(property).append("-").append(message).append(";");
        }
        return ResultVO.fail(ResponseCode.METHOD_ARGUMENT_NOT_VALID.getCode(), errorMessage.toString());
    }


    /**
     * 缺少请求参数
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResultVO handleMissingServletRequestParameterException(
            MissingServletRequestParameterException e, HttpServletRequest request) {
        log.warn("GlobalException:" + request.getRequestURI() + ":缺少请求参数:" + e.getParameterName());
        return ResultVO.fail(ResponseCode.METHOD_ARGUMENT_NOT_VALID.getCode(), "缺少请求参数");
    }

    /**
     * 参数类型传递错误
     */
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public ResultVO falseRequestParameterException(
            MethodArgumentTypeMismatchException m, HttpServletRequest request) {
        log.warn("GlobalException:参数类型错误 ,URL:{}", request.getRequestURI());
        return ResultVO.fail(ResponseCode.METHOD_ARGUMENT_NOT_VALID.getCode(), "参数类型错误");
    }


    /**
     * 400 - Bad Request
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResultVO handleHttpMessageNotReadableException(
            HttpMessageNotReadableException e, HttpServletRequest request) {
        log.warn("GlobalException:" + request.getRequestURI() + ":参数解析失败", e);
        return ResultVO.fail(ResponseCode.ERROR.getCode(), "参数解析失败");
    }


    @ExceptionHandler(LockFailureException.class)
    public ResultVO handleLockFailureException(HttpServletRequest request) {
        log.warn("handleLockFailureException:" + request.getRequestURI());
        return ResultVO.fail(ResponseCode.ERROR.getCode(), "释放锁异常");
    }

}
